import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class LogView extends StatefulWidget {
  const LogView({super.key});

  @override
  State<LogView> createState() => _LogViewState();
}

///iOS风格的弹窗
Future<void> _openCupertinoDialog(BuildContext context) async {
  final bool clean = await showCupertinoDialog(
    context: context,
    barrierDismissible: true,
    builder: (BuildContext context) {
      return CupertinoAlertDialog(
        title: const Text('注意'),
        content: const Text('是否清除日志？'),
        actions: [
          CupertinoDialogAction(
            child: const Text('取消', style: TextStyle(color: Colors.black)),
            onPressed: () {
              Navigator.pop(context, false); // 关闭对话框
            },
          ),
          CupertinoDialogAction(
            child: const Text('清除', style: TextStyle(color: Colors.blue)),
            onPressed: () {
              Navigator.pop(context, true); // 关闭对话框
            },
          ),
        ],
      );
    },
  );
  if (clean == false) {
    return;
  }
  Provider.of<LogNotifier>(context, listen: false).clear();
}

class _LogViewState extends State<LogView> {
  @override
  Widget build(BuildContext context) {
    final logNotifier = Provider.of<LogNotifier>(context);

    return SafeArea(
      child: Drawer(
        backgroundColor: Colors.black,
        child: Column(
          children: [
            ListTile(
              title: const Text(
                'Log',
                textAlign: TextAlign.left,
                style: TextStyle(color: Colors.white),
              ),
              leading: InkWell(
                  child: const Icon(
                    Icons.message,
                    color: Colors.redAccent,
                    size: 30,
                  ),
                  onTap: () {
                    _openCupertinoDialog(context);
                  }),
            ),
            Expanded(
              child: ListView.builder(
                padding: const EdgeInsets.only(left: 10),
                itemCount: logNotifier.logs.length,
                itemBuilder: (context, index) {
                  String item = logNotifier.logs[index];
                  bool isWrite = item.contains('写入') || item.contains('擦除');
                  String end = isWrite ? '' : '------------------------------';

                  return Text(
                    '$item\n$end',
                    style: const TextStyle(color: Colors.green, backgroundColor: Colors.black),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 使用例子： LogNotifier log = Provider.of<LogNotifier>(context, listen: false);
//    log.newLog('${date}:\n${per.result.device.platformName} => 已经连接');
///log状态管理
class LogNotifier extends ChangeNotifier {
  List<String> _logs = [];

  List<String> get logs => _logs;

  void newLog(String text) {
    try {
      _logs.add(text);
      notifyListeners();
    } catch (e) {
      // Handle the connection error
      print('Connection failed: ======$e');
    }
  }

  void clear() {
    try {
      _logs.clear();
      notifyListeners();
    } catch (e) {
      // Handle the connection error
      print('Connection failed: ======$e');
    }
  }

  ///
  static void addLog(BuildContext? context, String text) {
    if (context != null) {
      LogNotifier log = Provider.of<LogNotifier>(context, listen: false);
      log.newLog(text);
    }
  }
}
